<template>
  <el-card>
    <div slot="header">
      <h3>修改售价</h3>
    </div>
    <div>
      <LaunchReasonInput label="售价调价原因" :reason.sync="launchReason" />
      <el-divider />
      <BtnRender :render="renderBtnsBar" />
      <el-row>
        <SkusTable
          ref="skusTable"
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="TableInfo.list"
          :columns="TableInfo.columns"
          :loading="TableInfo.loading"
          @handleCancelSelect="handleRemoveRow"
        />
      </el-row>
    </div>
    <AssociateGoodsDialog
      ref="associateRef"
      :visible.sync="dialogVisible"
      :areaInfoMaps="areaInfoMaps"
      @getResults="updateTableListByAssociateGoods"
    />
    <senior-linked-dialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="updateTableListBySeniorLinked"
    >
      <LabelSelect
        bold
        clearable
        filterable
        label="销售区域"
        slot="conditionSlot"
        class="senior-select-wrap"
        :value.sync="seniorLinked.areaCode"
        :options="areaInfoMaps.areaOptions"
      />
    </senior-linked-dialog>
  </el-card>
</template>
<script>
import { mapGetters, mapMutations } from 'vuex';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import LabelSelect from '@/pages/commodity/components/LabelSelect';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import AssociateGoodsDialog from '@/components/AssociateGoods/sale-price/Edit';
import { TABLE_COLUMNS } from './constants';
import {
  getInitSaleDetails,
  processFrontendValidateResultsEdit,
  processBackendValidateResults,
  getSalesWithoutMessage
} from '@/utils/salePrice';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { TableInfo } from '@/utils/getUtils';
import { setAuthBtnId, createExcelByExport, generateUuid, isResponseSuccess } from '@/utils/bizUtils';
import {
  queryByIdsService,
  seniorQueryService,
  commitService,
  exportExcelService,
  importExcelUrl
} from '@/api/finance/salePriceManage/editSalePrice';
import { queryAreaInfoService } from '@/api/public';
export default {
  components: {
    BtnRender,
    SkusTable,
    LabelSelect,
    LaunchReasonInput,
    SeniorLinkedDialog,
    AssociateGoodsDialog
  },
  data () {
    return {
      launchReason: '', // 售价调价原因
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS, dimensionKey: 'id' }),
      btnLoading: {
        export: false,
        submit: false
      },
      dialogVisible: false,
      seniorLinked: {
        visible: false,
        columns: [{ label: 'SKU编码', prop: 'skuNo', type: 'textarea'}],
        dataSource: [{ skuNo: '' }],
        areaCode: '',
        isSenior: false
      },
      areaInfoMaps: {},
      saveAction: null, // 提交类型 - 1:暂存 2:提交
      recordNo: '', // 单据号。首次发起时为空
    }
  },
  created () {
    this.setAreaInfoMaps()
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    ...mapMutations('commonComps/associateGoods', ['CLEAR_ROWS']),
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const btnsBar = [
        { label: '高级关联', method: this.handleSeniorLined, hasAuth: true },
        { label: '关联商品', method: this.handleAssociateGoods, hasAuth: true },
        {
          label: '模板导入',
          action: importExcelUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          loadingFn: this.TableInfo.setLoading
        },
        {
          label: '模板导出',
          method: this.handleExport,
          loading: this.btnLoading.export,
          disabled: this.TableInfo.isNullList()
        },
        {
          label: '暂存',
          method: this.handleStash,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList(),
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          disabled: this.TableInfo.isNullList(),
        }
      ]
      return getListPageBtnsBar(h, btnsBar, this.showBtn)
    },
    // 删除
    handleRemoveRow ({ row }) {
      const filterList = this.TableInfo.list
        .filter(item => item[this.TableInfo.dimensionKey] != row[this.TableInfo.dimensionKey])
      this.TableInfo.setList(filterList)
      this.$refs?.associateRef?.deleteGoods(row) // 删除关联弹框对应已关联数据
    },
    // 高级关联
    handleSeniorLined () {
      setAuthBtnId('高级关联')
      this.seniorLinked.visible = true
    },
    // 关联商品
    handleAssociateGoods () {
      setAuthBtnId('关联商品')
      this.dialogVisible = true
    },
    // 模板导入 - 不需要重新计算售价（以导入数据为准）
    handleUploadSuccess (res) {
      if (isResponseSuccess(res)) {
        this.TableInfo.setList(res.retData)
      }
    },
    // 模板导出
    async handleExport () {
      this.exportUuid = generateUuid()
      const data = { uuid: this.exportUuid, sales: this.TableInfo.list }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportExcelService(data, loadingFn)
      createExcelByExport({ excelTitle: `修改售价_${this.exportUuid}`, res })
    },
    // 暂存
    handleStash () {
      this.saveAction = '1'
      this.processStashOrSubmit()
    },
    // 提交
    handleSubmit () {
      this.saveAction = '2'
      this.processStashOrSubmit()
    },
    // 暂存或提交
    processStashOrSubmit () {
      const callback = callbackArgs => {
        if (!callbackArgs) return this.fetchSubmitPriceList()
        const { list, columns, submitFlag } = callbackArgs
        this.TableInfo.setList(list)
        this.TableInfo.setColumns([...columns, ...TABLE_COLUMNS])
        if (submitFlag) this.fetchSubmitPriceList(submitFlag)
      }
      processFrontendValidateResultsEdit(this.TableInfo.list, callback)
    },
    // 提交请求
    async fetchSubmitPriceList (submitFlag) {
      const data = this.getCommitSaleParams(submitFlag)
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await commitService(data, loadingFn)
      if (!res) return
      if (res?.retData?.recordNo) this.recordNo = res.retData.recordNo // 只有后端返回单据号再进行赋值操作
      const ErrorMaps = res?.retData?.validates ?? {}
      const executeSuccessSubmitTask = () => {
        this.$message.success('操作成功')
        this.saveAction == '2' && this.$router.push({ name: 'chageFromManageList' }) // 提交时再跳转页面
      }
      const callback = callbackArgs => {
        if (!callbackArgs) return executeSuccessSubmitTask()
        const { list, columns, submitFlag } = callbackArgs
        this.TableInfo.setList(list)
        this.TableInfo.setColumns([...columns, ...TABLE_COLUMNS])
        if (submitFlag) this.fetchSubmitPriceList(submitFlag)
      }
      processBackendValidateResults(this.TableInfo.list, ErrorMaps, callback)
    },
    // 获取提交售价入参
    getCommitSaleParams (submitFlag) {
      const data = {
        recordNo: this.recordNo,
        launchReason: this.launchReason, // 售价调价原因
        saveAction: this.saveAction, // 操作类型 - 1:暂存 2:提交
        sales: getSalesWithoutMessage(this.TableInfo.list), // 售价信息
        submitFlag, // 仍要提交标志 - 当有异常提示时，必传1，如果不传，会一直保存不成功
        rawMaterialTodoRecordNo: this.$route?.query?.rawMaterialTodoRecordNo, // 原材料调价单号(原材料代办跳入时需传)
      }
      return data
    },
    // 根据关联uuid获取对应价格
    async getPriceByAssociateUuids (uuids) {
      const res = await queryByIdsService(uuids, this.TableInfo.setLoading)
      return res?.retData ?? {}
    },
    // 关联商品更新表格数据
    async updateTableListByAssociateGoods (results) {
      this.seniorLinked.isSenior = false
      if (!results) return this.TableInfo.setList([])
      const uuids = results.map(item => item[this.TableInfo.dimensionKey])
      const priceMaps = await this.getPriceByAssociateUuids(uuids)
      const fillPriceList = results.map(item => ({ ...item, ...(priceMaps[item.id] ?? {}) }))
      this.setRecalculatePriceList(fillPriceList)
    },
    // 高级查询更新表格数据
    async updateTableListBySeniorLinked (skuNos) {
      this.CLEAR_ROWS() // 清空关联商品已关联数据
      this.seniorLinked.isSenior = true
      const data = { skuNos, saleAreaCode: this.seniorLinked.areaCode }
      const res = await seniorQueryService(data, this.TableInfo.setLoading)
      if (res?.retData) this.setRecalculatePriceList(res.retData)
    },
    // 获取区域信息
    async setAreaInfoMaps () {
      const res = await queryAreaInfoService()
      const areaInfos = res?.retData ?? []
      const getUniqOptions = type => _.uniqBy(
        areaInfos.map(item => ({ value: item[`${type}Code`], label: item[`${type}Name`] })),
        'value'
      )
      const areaOptions = getUniqOptions('area')
      const provinceOptions = getUniqOptions('province')
      const cityOptions = getUniqOptions('city')
      this.areaInfoMaps = { areaOptions, provinceOptions, cityOptions } // 映射formItem prop属性
    },
    // 设置重新计算售价后的表格集合
    setRecalculatePriceList (list) {
      this.TableInfo.setList(getInitSaleDetails(list))
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-divider--horizontal {
  margin: 10px 0;
}
.senior-select-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
